package com.djp.computerServer.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.djp.computerServer.bean.Goods;
import com.djp.computerServer.bean.Package;
import com.djp.computerServer.service.GoodsService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Map;

@RestController
@RequestMapping("/goods")
public class GoodsController extends BaseController<GoodsService>{
    @RequestMapping("/getAll")
    @ResponseBody
    public Map getAll() {
        return buildMap("查询全部商品", service.getAll());
    }

    @RequestMapping("/add")
    @ResponseBody
    public Map add(@RequestBody Goods goods) {
        Goods goods1 = goods;

        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        for (Package p:goods.getPackages()){
            jsonObject = new JSONObject();
            jsonObject.put("title",p.getTitle());
            jsonObject.put("image",p.getImage());
            jsonObject.put("price",p.getPrice());
            jsonObject.put("num",p.getNum());
            jsonObject.put("describe",p.getDescribe());
            jsonObject.put("storeId",p.getStoreId());
            jsonArray.add(jsonObject);
        }
        goods1.setPackages(null);
        goods1.setPackageJson(Arrays.toString(jsonArray.toArray()));
        //return buildMap("添加商品", new ArrayList());
        return buildMap("添加商品", service.add(goods1));
    }

    @RequestMapping("/update")
    @ResponseBody
    public Map update(@RequestBody Goods goods) {
        return buildMap("修改商品信息", service.add(goods));
    }

    @RequestMapping("/get")
    @ResponseBody
    public Map getOne(@RequestBody Goods goods) {
        return buildMap("查询一个商品", service.getOne(goods));
    }
}
